#coding:utf-8

import json

import tornado.web
import tornado.websocket
import tornado.gen

import settings

if settings.STORAGE == "file":
    from models_file import Dm, Room

manager = None

class ConnectionManager(object):
    def __init__(self):
        if manager is not None:
            raise Exception("Cannot create more than one manager")
        self._listeners = {}

    def register_listener(self, room, listener):
        if room not in self._listeners:
            self._listeners[room] = set()
            self._listeners[room].add(listener)
        else:
            self._listeners[room].add(listener)

    def unregister_listener(self, room, listener):
        self._listeners[room].remove(listener)

    def broadcast_dm(self, room, dm):
        if room is None or room not in self._listeners:
            return

        for listener in self._listeners[room]:
            listener.on_dm_received(dm)

manager = ConnectionManager()

class LiveWsHandler(tornado.websocket.WebSocketHandler):
    @tornado.gen.coroutine
    def open(self, room):
        self._room = room
        manager.register_listener(room, self)

    def on_dm_received(self, dm):
        self.write_message(json.dumps(dm.dict()))

    def on_message(self, message):
        pass

    def on_close(self):
        manager.unregister_listener(self._room, self)

    def check_origin(self, origin):
        return True


class LivePollHandler(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self, room):
        self._room = room

        time = self.get_argument("time", None)
        
        result =  yield Dm.query(room, time)
        if result is None:
            raise tornado.web.HTTPError(404)

        self.write(json.dumps([dm.dict() for dm in result]))
